import Taro from '@tarojs/taro'
import { login, authorize } from './api'
import '@tarojs/async-await'

const appid = 'wx826cb99445ebac03';

// 获取微信登录凭证
export const wxLogin = async () => {
  try {
    const res = await Taro.login()
    return res.code
  } catch (error) {
    console.log('微信获取临时凭着失败')
  }
}

export const wxUserInfo = async () => {
  try {
    const res = await Taro.getUserInfo()
    console.log(res);
    const encryptedData = res.encryptedData;
    const iv = res.iv;
    const token = Taro.getStorageSync('token');
    const authRes: any = await authorize({
      appid,
      encryptedData,
      iv,
      token:token
    })
    return authRes;
  } catch (error) {
    console.log('获取用户信息失败')
  }
}

export const userLogin = async () => {
  try {
    await Taro.checkSession()
    if (!Taro.getStorageSync('token')) {
      throw new Error('本地没有缓存token')
    }
  } catch (error) {
    const code = await wxLogin()
    const loginRes: any = await login({
      code,
      appid,
    })
    Taro.setStorageSync('token', loginRes.token);
    return loginRes;
  }
}